﻿using CustomerServiceCenter.Helper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading;
using System.Web;

namespace CustomerServiceCenter.Models
{
    public class CEmail
    {
        private static string emailAccount = ConfigurationManager.AppSettings["systemAccount"].ToString();
        private static string passWord = ConfigurationManager.AppSettings["emailPassWord"].ToString();
        public static string PCEmailReturnMassage;
        public static bool sendEmailFlag = false;

        public static void sendEmailFunction(EmailInfo emailInfo)
        {
            Thread t1 = new Thread(new ThreadStart(sendEmailStart));
            Thread t2 = new Thread(new ParameterizedThreadStart(emailCompleted));
            t1.Start();
            t2.Start(emailInfo);
        }


        public static void sendEmailStart()
        {
            PCEmailReturnMassage = "邮件发送成功";
        }

        public  static void emailCompleted(object emailInfo)
        {
            //延时1秒
            EmailInfo information = (EmailInfo)emailInfo;
            System.Threading.Thread.Sleep(1000);
            sendEmailFlag = SendEmail(information.toEmailAddress, information.info);
            PCEmailReturnMassage = "邮件发送结果:\r\n" + (sendEmailFlag == true ? "邮件发送成功" : "邮件发送失败");
            //写入日志
        }

        public static bool SendEmail(string toEmailAddress, string info = "你有一封客户提醒，请注意查收！")
        {
            try
            {
                MailMessage message = new MailMessage();

                //设置邮件相关信息
                message.From = new MailAddress(emailAccount);
                message.To.Add(toEmailAddress);
                message.Subject = "Remind";
                message.Body = info;

                //设置邮件的服务器
                SmtpClient client = new SmtpClient("smtp.163.com");
                client.Credentials = new NetworkCredential(emailAccount, passWord);
                client.EnableSsl = true;
                client.Send(message);
                return true;
            }
            catch (SmtpException e)
            {
                return false;
            }
       }
    }

    public class EmailInfo{
        public string toEmailAddress { get; set; }
        public string info { get; set; }
    }

}